package xusage.cumulus.struts.filter;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.struts2.config.StrutsXmlConfigurationProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;

import xusage.cumulus.spring.resolver.CumulusResourcePatternResolver;

public class CumulusXmlConfigurationProvider extends StrutsXmlConfigurationProvider {

	private ServletContext context = null;
	
	public CumulusXmlConfigurationProvider() {
		super(false);
	}
	public CumulusXmlConfigurationProvider(boolean errorIfMissing) {
		super(errorIfMissing);
	}

	public CumulusXmlConfigurationProvider(String fileName, boolean errorIfMissing, ServletContext context) {
		super(fileName, errorIfMissing, context);
		this.context = context;
	}

	protected Iterator<URL> getConfigurationUrls(String fileName) throws IOException {
 		Iterator<URL> result = super.getConfigurationUrls(fileName);
 		if (result.hasNext()) { return result; }
    	List<URL> urls = new ArrayList<URL>();
    	ResourcePatternResolver resolver = new CumulusResourcePatternResolver(context);
    	Resource[] resources = resolver.getResources(fileName);    
    	for (Resource resource : resources) {
	    	try {
    			urls.add(resource.getURL());
	    	}
	    	catch (Exception ex) {
	            LOGGER.info("Unable to locate configuration files of the name {}, skipping", fileName);
	        }
    	}
		return urls.iterator();
	}
 	
	private static final Logger LOGGER = LoggerFactory.getLogger(CumulusXmlConfigurationProvider.class);
	
}
